package com.mx.beautiful;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.mx.beautiful.utils.ImageUtil;

import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ImageView.ScaleType;

public class MyApplication extends Application {
	public ExecutorService executorService = Executors.newFixedThreadPool(5);

	public void threadImage(ImageView v, String value, final Context context,
			final ListView listview) {
		final ImageView iv = v;
		final String url = value;
		final Handler handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				ImgData d = (ImgData) msg.obj;
				ImageView tempIv = (ImageView) listview.findViewWithTag(url);
				// tempIv.setLayoutParams(new LayoutParams(d.bit.getWidth(),
				// d.bit.getHeight()));
				if (tempIv != null) {
					tempIv.setScaleType(ScaleType.CENTER_CROP);
					tempIv.setImageBitmap(d.bit);
				}
			}
		};
		// v.setBackgroundResource(R.drawable.loading_img);
		v.setImageResource(R.drawable.load_img1);
		executorService.submit(new Runnable() {
			public void run() {
				try {
					int width = iv.getWidth();
					final Bitmap bitmap = ImageUtil.addImgDoubleCache(url,
							width, context,false);
					Message msg = new Message();
					msg.obj = new ImgData(bitmap, url);
					handler.sendMessage(msg);
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		});
	}
	
	public void threadImageOne(ImageView v, String value, final Context context,Boolean reLoad) {
		final ImageView iv = v;
		final Boolean ReLoad=reLoad;
		final String url = value;
		final Handler handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				ImgData d = (ImgData) msg.obj;
				
				iv.setImageBitmap(d.bit);
			}
		};
		// v.setBackgroundResource(R.drawable.loading_img);
		v.setImageResource(R.drawable.load_img1);
		executorService.submit(new Runnable() {
			public void run() {
				try {
					int width = iv.getWidth();
					final Bitmap bitmap = ImageUtil.addImgDoubleCache(url,
							width, context,ReLoad);
					Message msg = new Message();
					msg.obj = new ImgData(bitmap, url);
					handler.sendMessage(msg);
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		});
	}

	private class ImgData {
		public Bitmap bit;
		public String url;

		public ImgData(Bitmap _bit, String _str) {
			bit = _bit;
			url = _str;
		}
	}
}
